package org.skycloud.mybatis.dialect.impl;

import org.apache.ibatis.session.RowBounds;
import org.skycloud.mybatis.dialect.Dialect;
import org.skycloud.mybatis.utils.StringBuilderUtils;

public final class DB2Dialect implements Dialect {

	private static final String FETCH_FIRST = " fetch first ";
	private static final String ROWS_ONLY = " rows only";
	private static final String SELECT = "select * from ( select inner2_.*, rownumber() over(order by order of inner2_) as rownumber_ from ( ";
	private static final String ROWS_ONLY_WITH_WHERE = " rows only ) as inner2_ ) as inner1_ where rownumber_ > ";
	private static final String ORDER_BY = " order by rownumber_";

	@Override
	public String getSql(String sql, RowBounds rowBounds) {
		if (rowBounds.getOffset() > 0) {
			return StringBuilderUtils.getThreadLocalStringBuilder(0).append(SELECT).append(sql).append(FETCH_FIRST)
					.append(rowBounds.getLimit()).append(ROWS_ONLY_WITH_WHERE).append(rowBounds.getOffset())
					.append(ORDER_BY).toString();
		} else {
			return StringBuilderUtils.getThreadLocalStringBuilder(0).append(sql).append(FETCH_FIRST)
					.append(rowBounds.getLimit()).append(ROWS_ONLY).toString();
		}
	}
}
